package com.example.demo.mqsever.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

// 交换机类
public class Exchange {

    private String name ;
    // 交换机类型, 默认直接交换机
    private ExchangeType type = ExchangeType.DIRECT;
    // 是否持久化存储,设置开关决定
    private boolean durable = false;
    // 自动删除无用交换机
    private boolean autoDelete = false;
    // 额外的参数
    private Map<String,Object> arguments = new HashMap<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ExchangeType getType() {
        return type;
    }

    public void setType(ExchangeType type) {
        this.type = type;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

//     让 argument 参数可以加入到数据库中，不使用系统自动生成的 get 和 sat
//    public Map<String, Object> getArguments() {
//        return arguments;
//    }
//
//    public void setArguments(Map<String, Object> arguments) {
//        this.arguments = arguments;
//    }

    // 用于数据库
    public String getArguments(){
        // Map 类型转换为 String（json），数据库无法存储 Map
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return "{}";
    }

    public void setArguments(String arguments){
        // String（json） 类型转换为 Map
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(arguments, new TypeReference<HashMap<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    // 用于 java 内部代码调用（例如测试类）
    public Object getArguments(String key){
        return arguments.get(key);
    }

    public void setArguments(String key, Object value){
        arguments.put(key,value);
    }

    public void setArguments(Map<String,Object> arguments){
        this.arguments = arguments;
    }

}
